// pages/itemsubmit/itemsubmit.js
var QQMapWX = require('../../qqmap-wx-jssdk.min.js');
 
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    key: '6FTBZ-OPECR-OYVWT-WULAV-V7VPQ-FAFCT' // 必填
});

Page({

  /**
   * 页面的初始数据
   */
  data: {
    state:"",
    itemid:"",
    //标题
    title:'',
    //文本介绍
    intro:'',
    //图片
    picurls:[],
    picslen:"",
    types:['学习必备','品质生活','影娱数码',
          '健康锻炼','潮玩服饰','技能教学','其他类型']
          ,
    select:false,
    //物品类型
    itemtype:'请选择类型',
    typeindex:'',
    //日租金
    rentmoney:"",
    deposit:"",
    lease:false,
    //联系方式
    phone:'',
    wxnumber:'',
    qqnumber:'',
    rentways:[
      {choose:false,
        type:'送货上门'}
      ,{choose:false,
        type:'物品自提'},
      {choose:false,
        type:'当面交易'}],
    address:'',
  },
  onLoad(options){ 
    // console.log(options)
    var that = this;
    

    if(options.itemid){
      that.setData({
        itemid:options.itemid,
        state:options.rentState
      })
      // console.log(that.data.itemid)
      wx.request({
        url: 'http://127.0.0.1:8080/item/selectItemById',
        method:"POST",
        data:{
          itemid:that.data.itemid
        },
        success(res){
          // console.log(res);
          var iteminfo = res.data[0];
          
          var lease = false;
          if(iteminfo.isRent == "是"){
            lease = true;
          }

          for(var i=0;i<iteminfo.rentWay.length;i++){
            var rentways = 'rentways['+iteminfo.rentWay[i]+'].choose';
            that.setData({
              [rentways]:true
            })
          }
          // console.log(iteminfo.rentWay.length)
          console.log(JSON.parse(iteminfo.itemPic).length)
          // 物品类型判断
          that.setData({
            title:iteminfo.itemTitle,
            intro:iteminfo.itemInfo,
            picurls:JSON.parse(iteminfo.itemPic),
            itemtype:iteminfo.itemType,
            lease:lease,
            picslen:JSON.parse(iteminfo.itemPic).length,
            rentmoney:iteminfo.dayRent,
            deposit:iteminfo.deposit,
            phone:iteminfo.contactPhone,
            wxnumber:iteminfo.contactWx,
            qqnumber:iteminfo.contactQq,
            address:iteminfo.sendAddress
          })
        }
      })
    }
  },

  //获取输入信息
  title(e){
    this.setData({
      title:e.detail.value
    })
  },
  intro(e){
    this.setData({
      intro:e.detail.value
    })
  },
  rent(e){
    this.setData({
      rentmoney:e.detail.value
    })
  },
  deposit(e){
    this.setData({
      deposit:e.detail.value
    })
  },
  islease(e){
    var value = this.data.lease
    this.setData({
      lease:!value
    })
  },
  phone(e){
    this.setData({
      phone:e.detail.value
    })
  },
  wxnumber(e){
    this.setData({
      wxnumber:e.detail.value
    })
  },
  QQnumber(e){
    this.setData({
      qqnumber:e.detail.value
    })
  },


  //添加照片
  selectpic(e){
    console.log(this.data.picurls)
    let that = this;
    wx.chooseImage({
      count: 9,
      success(res){
        var picurls = that.data.picurls.concat(res.tempFilePaths)
        that.setData({
          picurls:picurls
        })
        console.log(that.data.picurls)
      }
    })
  },
  //删除照片
  delpic(e){
    console.log(e)
    let that = this;
    var index = e.currentTarget.dataset.index;
    var del = this.data.picurls
    wx.showModal({
      content: '是否删除该照片',
      title: '提示',
      success(res){
        if(res.confirm){
          del.splice(index,1)
          that.setData({
            picurls:del
          })
      console.log(that.data.picurls)
        }
      },
    })  
  },
  // 查看图片
  showpic(e){
    var index  =e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.picurls[index],     //当前图片地址
      urls: this.data.picurls,                 //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //打开种类选择框
  choosetype(e){
    var select = this.data.select
    this.setData({
      select:!select
    })
  },
  //选择物品类型
  itemtype(e){
    console.log(e)
    var index = e.currentTarget.dataset.index;
    console.log(index)
    this.setData({
      select:false,
      itemtype:this.data.types[index],
      typeindex:index
    })
  },
  //选择收货方式
  chooseway(e){
    var index = e.currentTarget.dataset.index;
    var choose = 'rentways['+index+'].choose';
    var value = this.data.rentways[index].choose;
    this.setData({
      [choose]:!value
    })
  },
  address(e){
    this.setData({
      address:e.detail.value
    })
  },
  //展示地址位置
  showaddress(e){
    var _this = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: _this.data.address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function(res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        //根据地址解析在地图上标记解析地址位置
        _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
          markers: [{
            id: 0,
            title: res.title,
            latitude: latitude,
            longitude: longitude,
            iconPath: '/pic/地标.png',//图标路径
            width: 30,
            height: 30,
            // callout: { //可根据需求是否展示经纬度
            //   content: latitude + ',' + longitude,
            //   color: '#000',
            //   display: 'ALWAYS'
            // }
          }],
          poi: { //根据自己data数据设置相应的地图中心坐标变量名称
            latitude: latitude,
            longitude: longitude
          },
        });

        wx.openLocation({
          latitude:latitude,
          longitude:longitude,
          address: _this.data.address,
          name: _this.data.address,
          scale: 28,
        })
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
    })
  },

  // 存草稿
  save(e){
    // wx.request({
    //   url: 'http://127.0.0.1:8080/item/selectItem',
    //   method:"POST",
    //   data:{openid:wx.getStorageSync('openid')},
    //   success(res){
    //     console.log(res)
    //   }
    // })
      //标识挑选收货地址的方法
      var target = '';
      for(var i=0;i<this.data.rentways.length;i++)
      {
        if(this.data.rentways[i].choose == true)
          target = target+i
      }

      var that = this;
      var data1 = this.data;

      
    //第一次存草稿
    if(this.data.itemid == ""){

      var arr = [];
      var  h = this.data.picurls.length;
      var i =0;
      for (i = 0; i < h; i++) {
      //上传文件
      // console.log(i,h)
      wx.uploadFile({
        url: 'http://127.0.0.1:8080/image/upload',
        filePath: this.data.picurls[i],
          name: "file",
          header: {
            "content-type": "multipart/form-data"
          },
          success: function ({ data: res }) {
            console.log(res)
            res = JSON.parse(res);
            const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
            // console.log(pic_url)
            // 图片路径集合
            arr.unshift(pic_url);
          },
          fail: function (err) {
            wx.showToast({
              title: "上传失败",
              icon: "error",
              duration: 2000
            })
          },
          complete: function (result) {
            // console.log(result.errMsg)
          }
        })
      }

      setTimeout(function(){
        if(data1.title != "" || data1.intro != "" || data1.picurls.length != 0 || data1.itemtype !="请选择类型" || data1.rentmoney != "" || data1.deposit != "" || target != "" || data1.address !=""){
          var newDateTime=new Date().getTime();
        console.log("i"+newDateTime);

        var type = "请选择类型";
        if(data1.itemtype != "请选择类型"){
          type = data1.itemtype;
        }

        var rentmoney = 0
        if(data1.rentmoney != ""){
          rentmoney = data1.rentmoney;
        }

        var deposit = 0
        if(data1.deposit != ""){
          deposit = data1.deposit;
        }

        // 当前时间
        console.log(arr)
        var submittime = new Date().toISOString().substring(0, 10);
        var data = {
          itemid:"i"+newDateTime,
          title:data1.title,
          intro:data1.intro,
          itempic:JSON.stringify(arr),
          submittime:submittime,
          dayrent:rentmoney,
          deposit:deposit,
          phone:data1.phone,
          wxnumber:data1.wxnumber,
          qqnumber:data1.qqnumber,
          rentways:target,
          itemtype:type,
          conrent:(data1.lease ? "是" : "否"),
          userid:wx.getStorageSync('openid'),
          address:data1.address
        }
        console.log(data)
        wx.request({
          url: 'http://127.0.0.1:8080/item/saveItem',
          method:"POST",
          data:data,
          success(res){
            // console.log(res)
            if(res.data){
              wx.showToast({
                title: '保存成功',
                duration: 1000,
                icon: "success",
                success: (res) => {},
              })
              wx.navigateBack({
                delta: 1
              });
            }else{
              wx.showToast({
                title: '发布失败',
                duration: 1000,
                icon: "error",
                success: (res) => {},
              })
            }
          }
        }) 
        }else{
          wx.showToast({
            title: '至少填写一项',
            icon:"error"
          })
        }
      },10)
    }else{
      // console.log(that.data.picslen)
      var arr =[]
      if(that.data.picslen != 0){
        arr = that.data.picurls
      }
      // console.log(2222222222222222)
      // console.log(arr)
      var  h = this.data.picurls.length;
      
      for ( var i = that.data.picslen; i < h; i++) {
      //上传文件
      // console.log(i,h)
      wx.uploadFile({
        url: 'http://127.0.0.1:8080/image/upload',
        filePath: that.data.picurls[i],
          name: "file",
          header: {
            "content-type": "multipart/form-data"
          },
          success: function ({ data: res }) {
            // console.log(res)
            res = JSON.parse(res);
            const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
            // console.log(pic_url)
            // 图片路径集合
            arr.unshift(pic_url);
            // console.log(888888)
      // console.log(arr)
            
          },
          fail: function (err) {
            wx.showToast({
              title: "上传失败",
              icon: "error",
              duration: 2000
            })
          },
          complete: function (result) {
            // console.log(result.errMsg)
          }
        })
      }

     
      setTimeout(function(){

       if(that.data.picslen != 0){
         arr.splice(h,h-that.data.picslen)
       }
        
        if(data1.title != "" || data1.intro != "" || data1.picurls.length != 0 || data1.itemtype !="请选择类型" || data1.rentmoney != "" || data1.deposit != "" || target != "" || data1.address !=""){
         

        var type = "请选择类型";
        if(data1.itemtype != "请选择类型"){
          type = data1.itemtype;
        }

        var rentmoney = 0
        if(data1.rentmoney != ""){
          rentmoney = data1.rentmoney;
        }

        var deposit = 0
        if(data1.deposit != ""){
          deposit = data1.deposit;
        }

        // 当前时间
        var submittime = new Date().toISOString().substring(0, 10);
        var data = {
          itemid:that .data.itemid,
          title:data1.title,
          intro:data1.intro,
          itempic:JSON.stringify(arr),
          submittime:submittime,
          dayrent:rentmoney,
          deposit:deposit,
          phone:data1.phone,
          wxnumber:data1.wxnumber,
          qqnumber:data1.qqnumber,
          rentways:target,
          itemtype:type,
          conrent:(data1.lease ? "是" : "否"),
          address:data1.address
        }
        // console.log(data)
        wx.request({
          url: 'http://127.0.0.1:8080/item/updateItem',
          method:"POST",
          data:data,
          success(res){
            // console.log(res)
            if(res.data){
              wx.showToast({
                title: '保存成功',
                duration: 1000,
                icon: "success",
                success: (res) => {},
              })
              wx.navigateBack({
                delta: 1,
              });
            }else{
              wx.showToast({
                title: '发布失败',
                duration: 1000,
                icon: "error",
                success: (res) => {},
              })
            }
          }
        }) 
        }else{
          wx.showToast({
            title: '至少填写一项',
            icon:"error"
          })
        }
      },100)
    }
  },

  // 发布物品
  submit(e){
    
    var that = this;
    var data1 = this.data;

    //标识挑选收货地址的方法
    var target = '';
    for(var i=0;i<this.data.rentways.length;i++)
    {
      if(this.data.rentways[i].choose == true)
        target = target+i
    }

    // console.log(target)
    // console.log(this.data)

    if(data1.title != "" && data1.intro != "" && data1.picurls.length != 0 && data1.itemtype !="请选择类型" && data1.rentmoney != "" && data1.deposit != "" && target != "" && data1.address !=""){

      if(data1.phone == "" && data1.wxnumber == "" && data1.qqnumber == ""){
        wx.showToast({
          title: '至少填写一种联系方式',
          duration: 1000,
          icon: "error",
          success: (res) => {},
        })
      }else{
        wx.showModal({
          title: '确定发布该物品',
          content: '',
          complete: (res) => {
            if (res.confirm) {
              //上传完成后把文件上传到服务器
              if(that.data.itemid == ""){
                var arr = []
                var  h = this.data.picurls.length;
                var i =0;
                for (i = 0; i < h; i++) {
                //上传文件
                console.log(i,h)
                wx.uploadFile({
                  url: 'http://127.0.0.1:8080/image/upload',
                  filePath: this.data.picurls[i],
                    name: "file",
                    header: {
                      "content-type": "multipart/form-data"
                    },
                    success: function ({ data: res }) {
                      console.log(res)
                      res = JSON.parse(res);
                      const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
                      // console.log(pic_url)
                      // 图片路径集合
                      arr.unshift(pic_url);
                    },
                    fail: function (err) {
                      wx.showToast({
                        title: "上传失败",
                        icon: "error",
                        duration: 2000
                      })
                    },
                    complete: function (result) {
                      // console.log(result.errMsg)
                    }
                  })
                }
    
                setTimeout(function(){
                  var newDateTime=new Date().getTime();
                  console.log("i"+newDateTime);
      
                  // 当前时间
                  console.log("48586546568768756")
                  console.log(arr)
                  var submittime = new Date().toISOString().substring(0, 10);
                  var data = {
                    itemid:"i"+newDateTime,
                    title:data1.title,
                    intro:data1.intro,
                    itempic:JSON.stringify(arr),
                    submittime:submittime,
                    dayrent:data1.rentmoney,
                    deposit:data1.deposit,
                    phone:data1.phone,
                    wxnumber:data1.wxnumber,
                    qqnumber:data1.qqnumber,
                    rentways:target,
                    itemtype:data1.itemtype,
                    conrent:(data1.lease ? "是" : "否"),
                    address:data1.address,
                    userid:wx.getStorageSync('openid')
                  }
                  console.log(data)
                  wx.request({
                    url: 'http://127.0.0.1:8080/item/submitItem',
                    method:"POST",
                    data:data,
                    success(res){
                      console.log(res)
                      if(res.data){
                        wx.showToast({
                          title: '发布成功',
                          duration: 1000,
                          icon: "success",
                          success: (res) => {},
                        })
                        wx.navigateBack({
                          delta: 1
                        });
                      }else{
                        wx.showToast({
                          title: '发布失败',
                          duration: 1000,
                          icon: "error",
                          success: (res) => {},
                        })
                      }
                    }
                  }) 
                },100)
              }else{
                
                var arr = []
                if(that.data.picslen != 0){
                  arr = that.data.picurls
                }
                // console.log(arr)
                // console.log(that.data.picslen)
                var  h = this.data.picurls.length;
                var i;
                for (i = that.data.picslen; i < h; i++) {
                //上传文件
                console.log(i,h)
                wx.uploadFile({
                  url: 'http://127.0.0.1:8080/image/upload',
                  filePath: this.data.picurls[i],
                    name: "file",
                    header: {
                      "content-type": "multipart/form-data"
                    },
                    success: function ({ data: res }) {
                      // console.log(res)
                      res = JSON.parse(res);
                      const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
                      // console.log(pic_url)
                      // 图片路径集合
                      arr.unshift(pic_url);
                    },
                    fail: function (err) {
                      wx.showToast({
                        title: "上传失败",
                        icon: "error",
                        duration: 2000
                      })
                    },
                    complete: function (result) {
                      // console.log(result.errMsg)
                    }
                  })
                }
    
                setTimeout(function(){
                  // var newDateTime=new Date().getTime();
                  // console.log("i"+newDateTime);
                  if(that.data.picslen != 0){
                    arr.splice(h,h-that.data.picslen)
                  }
      
                  // 当前时间
                  // console.log("48586546568768756")
                  // console.log(arr)
                  var submittime = new Date().toISOString().substring(0, 10);
                  var data = {
                    itemid:data1.itemid,
                    title:data1.title,
                    intro:data1.intro,
                    itempic:JSON.stringify(arr),
                    submittime:submittime,
                    dayrent:data1.rentmoney,
                    deposit:data1.deposit,
                    phone:data1.phone,
                    wxnumber:data1.wxnumber,
                    qqnumber:data1.qqnumber,
                    rentways:target,
                    itemtype:data1.itemtype,
                    conrent:(data1.lease ? "是" : "否"),
                    address:data1.address,
                  }
                  // console.log(data)
                  wx.request({
                    url: 'http://127.0.0.1:8080/item/addNoItem',
                    method:"POST",
                    data:data,
                    success(res){
                      // console.log(res)
                      if(res.data){
                        wx.showToast({
                          title: '发布成功',
                          duration: 1000,
                          icon: "success",
                          success: (res) => {},
                        })
                        wx.navigateBack({
                          delta: 1
                        });
                      }else{
                        wx.showToast({
                          title: '发布失败',
                          duration: 1000,
                          icon: "error",
                          success: (res) => {},
                        })
                      }
                    }
                  }) 
                },100)
              }
            
            }
          }
        })
       
      }
    }else{
      wx.showToast({
        title: '物品信息不完整',
        duration: 1000,
        icon: "error",
        success: (res) => {},
      })
    }

    
    
   

    
    
  }


  
})